import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Liu, Yunfeng
 * @DateTime: 2021/7/18 21:11
 * @Description: TODO
 */
public class groupAnagrams {
    public static List<List<String>> groupAnagrams(String[] strs) {
        if(strs == null || strs.length == 0){
            return Collections.EMPTY_LIST;
        }
        Map<String, List<String>> map  = new HashMap<>();
        for(String s : strs){
            String sortedString = sortedString(s);
            if(map.keySet().contains(sortedString)){
                List<String>addedList = map.get(sortedString);
                addedList.add(s);
            }else{
                List<String> newList = new ArrayList<>();
                newList.add(s);
                map.put(sortedString,newList);
            }
        }
        return map.values().stream().collect(Collectors.toList());
    }

    private static String sortedString(String s){
        char[] chars =  s.toCharArray();
        Arrays.sort(chars);
        return String.valueOf(chars);
    }

    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
       groupAnagrams(strs).stream().forEach(strings -> {
           System.out.println(strings);
       });
    }
}
